// 定义蛇类方法接口
interface createBody {
    createBody(): void;
}
interface move {
    move(): void;
}
interface borderLimit {
    borderLimit(timer:number): void;
}

import Rect from './rect'

class Snake implements createBody, move, borderLimit {
    body: Rect[];
    speed: number;
    timer: number;
    dir: string;
    container: HTMLElement;
    head: Rect;
    leftNum:number;
    topNum:number;
    constructor(containerName: string) {
        this.body = [];
        this.speed = 10;
        this.timer = null;
        this.dir = "right";
        this.leftNum;
        this.topNum;
        for (let i = 0; i < 4; i++) {
            let rect;
            if (i == 3) {
                rect = new Rect(i * 50, 0, "red");
                this.head = rect;
            } else {
                rect = new Rect(i * 50, 0);
            }
            this.body.unshift(rect);
        }

        this.container = document.querySelector(containerName)
        this.createBody();
    }
    createBody() {
        this.body.forEach(item => {
            item.createRect(this.container);
        })
    }
    move() {

        let leftNum = this.head.getleft();
        let topNum = this.head.getTop();
        this.leftNum = leftNum;
        this.topNum = topNum;
        switch (this.dir) {
            case 'left':
                this.head.setLeft(leftNum - 50);
                break;
            case 'right':
                this.head.setLeft(leftNum + 50);
                break;
            case 'up':
                this.head.setTop(topNum - 50);
                break;
            case 'down':
                this.head.setTop(topNum + 50);
                break;
        }
    }

    borderLimit(timer:number) {
        let leftNum = this.head.getleft();
        let topNum = this.head.getTop();
        if (leftNum < 0 || leftNum >= 550) {
            console.log("碰撞了");
            clearInterval(timer);
        }
        if (topNum < 0 || topNum >= 550) {
            console.log("碰撞了");
            clearInterval(timer);
        }
    }
}

export default Snake;